<template>
  <Container class="gift-add">
    <div class="container-header group" slot="header">
      <CouponNameSelect class="start w260" v-model="couponId" :couponSendChannel="couponSendChannelEnum"></CouponNameSelect>
      <Button type="primary" :loading="loading" class="btn-search" @click="onClickAdd">添加券</Button>
    </div>
    <Tabs v-model="tab">
      <Button slot="extra" type="primary" @click="toListPage">返回列表页</Button>
      <TabPane label="包含的券" name="tab1">
        <homeTable
            :list="list"
            @getData="getData"
            @onPageSizeChange="onPageSizeChange"
            @onPageChange="onPageChange"
          />
      </TabPane>
    </Tabs>
    <ChangeNum ref="change-num" @complete="getData"/>
  </Container>
</template>
<script>
import homeTable from '~/homeTable'
import { clearEmpty } from '@/util'
import CouponNameSelect from '~/CouponNameSelect'
import GiftBagNextData from './edit/GiftBagNextData'
import ChangeNum from './edit/ChangeNum'
export default {
  components: {
    CouponNameSelect,
    homeTable,
    ChangeNum
  },
  data() {
    /**
     * NONE_LIMIT(0, "不限")
     * TIRE_INSURANCE(1, "轮胎保小程序")
     * CLOUD_APP(2, "中策云店")
     * SALESMAN(3, "业务通")
     */
    return {
      couponPackageId: window.localStorage.getItem('couponPackageId'),
      couponSendChannelEnum: window.localStorage.getItem('couponSendChannelEnum'),
      packageName: window.localStorage.getItem('packageName'),
      tab: 'tab1',
      couponId: null,
      list: GiftBagNextData,
      loading: false
    }
  },
  destroyed() {
    this.$bus.$off()
  },
  mounted() {
    this.list.currentPage =  ~~this.$route.query.currentPage || 1;
    this.list.pageSize = ~~this.$route.query.pageSize || this.list.pageSize;
    this.$bus.$on('onChange', ({id, quantity}) => {this.onChange(id, quantity)})
    this.$bus.$on('onDelete', ({id, index}) => {this.onDelete(id, index)})
		this.getData();
  },
  beforeRouteLeave(to, from, next) {
    window.localStorage.removeItem('couponSendChannelEnum')
    window.localStorage.removeItem('packageName')
    window.localStorage.removeItem('couponPackageId')
    next()
  },
  methods: {
    getData() {
      let param = {
        current: this.list.currentPage,
        size: this.list.pageSize,
        couponPackageId: this.couponPackageId,
        couponName: this.list.form.couponName
      }
      param = clearEmpty(param)
      this.list.status = "loading"
      this.$jsonPost("/coupon/coupon_package/item_page", param).then(data => {
        this.loading = false
        this.list.data = []
        this.list.totalItem = Number(data.total)
        this.list.data = (data.records || [])
        this.list.status = "pass"
      }).catch(() => {  
        this.list.status = "error"
      })
    },
    onClickAdd() {
      if (!this.couponId || !this.couponPackageId || this.loading) return
      this.loading = true
      let params = {
        couponId: this.couponId,
        couponPackageId: this.couponPackageId,
        quantity: 1
      }
      this.$jsonPost('/coupon/coupon_package/add_coupon', params).then(data => {
        this.getData()
      }).catch(() => {
        this.loading = false
      })
    },
    onChange(id, quantity) {
      this.$refs['change-num'].updateForm(id, quantity)
    },
    onDelete(id, index) {
      this.$Modal.confirm({
        title: '删除',
        content: '确定删除所选券？',
        onOk: () => {
          this.$ajaxPost(`/coupon/coupon_package/delete_coupon/${id}`).then(() => {
            this.$Notice.success({
              title: '删除成功'
            })
            this.list.data.splice(index, 1)
          })
        }
      })
    },
    toListPage() {
      this.$router.push({
        name: 'sales/giftbag/list'
      })
    },
    onPageChange(number) {
			this.list.currentPage = number;
			this.$router.push({
				name: "sales/giftbag/next",
				query: {
					currentPage: this.list.currentPage,
					pageSize: this.list.pageSize
				}
			});
      this.getData();
		},
    onPageSizeChange(pageSize) {
			this.list.currentPage = 1;
			this.list.pageSize = pageSize;
			this.$router.push({
				name: "sales/giftbag/next",
				query: {
					currentPage: this.list.currentPage,
					pageSize: this.list.pageSize
				}
			});
			this.getData();
		}
  },
  watch: {
		$route() {
			let page = ~~this.$route.query.currentPage;
			let table = this.list;
			if (table.currentPage !== page) {
				table.currentPage = ~~this.$route.query.currentPage === 0 ? 1 : ~~this.$route.query.currentPage;
				this.getData();
			}
		}
	}
}
</script>